﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

public partial class Invoice : System.Web.UI.Page, ICallbackEventHandler
{
    Dictionary<string, string> ClientRequest = null;
    Dictionary<string, string> ClientResponse = null;
    JavaScriptSerializer serializer;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            CallBackReference();
            if (!IsPostBack)
            {
                if (SessionInfo.prop_getObj.EmployeeID == 0)
                    Response.Redirect("login.aspx");
                else
                {
                    PLMstFormMasters objRights = CommonUtil.CheckRightsForForm("2");
                    if (objRights.ViewAccess == false)
                        Response.Redirect("Login.aspx");
                    if (Request.Params.Count > 0 && Request.Params[0] == "Excel")
                    {
                        UI_ExportToExcel();
                    }

                    cboCompany.Focus();
                    UI_Filldropdowns();
                    SessionInfo.prop_getObj.InvoiceEntrySearchCriteria = new PLInvoice();
                    grdResult.DataSource = new BL_Invoice().BL_fnGetInvoiceTransactions(new PLInvoice() { IsCompleted = false });
                    grdResult.DataBind();
                }
            }
        }
    }

    protected void UI_Filldropdowns()
    {
        List<PLCompany> objCompanies = new BL_Company().BL_fnGetCompanyNameList(new PLCompany() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboCompany, objCompanies, "CompanyID", "Name");
        CommonUtil.LoadDropdown(cboAddCompany, objCompanies, "CompanyID", "Name", "[Select Company]");

        List<PLClient> objClients = new BL_Client().BL_fnGetClientNameList(new PLClient() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboClient, objClients, "ClientID", "ClientName");
        //CommonUtil.LoadDropdown(cboAddClient, objClients, "ClientID", "ClientName", "[Select Client]");

        List<PLContract> objContracts = new BL_Contract().BL_fnGetContractNameList(new PLContract() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboContract, objContracts, "ContractID", "ContractName");
        //CommonUtil.LoadDropdown(cboAddContract, objContracts, "ContractID", "ContractName", "[Select Contract]");

        List<PLPaymentMode> objPaymentMode = new BL_PaymentMode().BL_fnGetPaymentModeNameList(new PLPaymentMode() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboPaymentMode, objPaymentMode, "PaymentModeID", "PaymentModeName");
    }

    // Override the Render method to ensure that this control
    // is nested in an HtmlForm server control, between a <form runat=server>
    // opening tag and a </form> closing tag.
    protected override void Render(HtmlTextWriter writer)
    {
        // Ensure that the control is nested in a server form.
        if (Page != null)
        {
            Page.VerifyRenderingInServerForm(this);
        }
        base.Render(writer);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    protected void UI_ExportToExcel()
    {
        if (SessionInfo.prop_getObj.InvoiceEntrySearchCriteria != null)
        {
            List<PLInvoice> objInvoiceList = new BL_Invoice().BL_fnGetInvoiceTransactions(SessionInfo.prop_getObj.InvoiceEntrySearchCriteria);
            int intIncrementer = 0;
            var varInvList = (from l in objInvoiceList
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  Company = l.CompanyName,
                                  Client = l.ClientName,
                                  Contract = l.ContractName,
                                  PaymentMode = l.PaymentModeName,
                                  ContractNo = l.ContractNo,
                                  InvoiceNo = l.InvoiceNo,
                                  InvoiceDate = l.InvoiceDate.ToString("dd/MM/yyyy"),
                                  ContractPer = l.PaymentLevelPer,
                                  GrossAmt = l.GrossInvoiceAmount,
                                  ServiceTaxPer = l.ServiceTaxPer,
                                  ServiceTaxAmt = l.ServiceTaxAmount,
                                  FinalInvAmt = l.FinalInvoiceAmount,
                                  Completed = (l.IsCompleted == true ? "Yes" : "No")
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Company", "Client", "Contract", "Payment Mode", "Contract #", "Invoice #", "Invoice Date", "Contract %", "Gross Amt.", "Service Tax %", "Service Tax Amt.", "Final Invoice Amt.", "Completed" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Invoice List");
        }
        else
        {
            Response.End();
        }
    }

    #region callback functions
    public void CallBackReference()
    {
        string strReference = Page.ClientScript.GetCallbackEventReference(this, "args", "getResponse", "context", "ClientCallbackError", true);
        string strScript = " function UseCallback(args,context) { " + strReference + " ; } ";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", strScript, true);
    }

    public string GetCallbackResult()
    {
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        oSerializer.MaxJsonLength = GlobalDefaultValues.MaxJsonLength;
        return oSerializer.Serialize(ClientResponse);
    }

    public void RaiseCallbackEvent(string strEventArgument)
    {
        try
        {
            serializer = new JavaScriptSerializer();
            ClientRequest = serializer.Deserialize<Dictionary<string, string>>(strEventArgument);
            ClientResponse = new Dictionary<string, string>();
            string Track = ClientRequest["Track"];
            ClientResponse = new Dictionary<string, string>();
            ClientResponse["Track"] = Track;
            if (SessionInfo.prop_getObj.EmployeeID == 0)
            {
                ClientResponse["SessionTimeOut"] = "1";
            }
            else
            {
                ClientResponse["SessionTimeOut"] = "0";
                if (Track.Equals("GetSearchResult"))
                {
                    UI_SearchResult();
                }
                if (Track.Equals("T_FillClients"))
                {
                    PLContract objContract = new PLContract();
                    objContract.CompanyID = TrynParse.parseInt(ClientRequest[cboAddCompany.ID]);
                    UI_FillClients(objContract);
                }
                if (Track.Equals("T_FillContracts"))
                {
                    PLContract objContract = new PLContract();
                    objContract.CompanyID = TrynParse.parseInt(ClientRequest[cboAddCompany.ID]);
                    objContract.ClientID = TrynParse.parseInt(ClientRequest[cboAddClient.ID]);
                    UI_FillContracts(objContract);
                }
                if (Track.Equals("T_FillTrnContracts"))
                {
                    PLContract objContract = new PLContract();
                    objContract.CompanyID = TrynParse.parseInt(ClientRequest[cboAddCompany.ID]);
                    objContract.ClientID = TrynParse.parseInt(ClientRequest[cboAddClient.ID]);
                    objContract.ContractID = TrynParse.parseInt(ClientRequest[cboAddContract.ID]);
                    UI_FillTrnContracts(objContract);
                }
                if (Track.Equals("DeleteRecord"))
                {
                    UI_DeleteRecord();
                }
                if (Track.Equals("T_FillTrnContractsDetails"))
                {
                    UI_FillTrnContractsDetails();
                }
                if (Track.Equals("EdiRecord"))
                {
                    UI_EditRecord();
                }
                else if (Track.Equals("InsertEditDetails"))
                {
                    PLInvoice objInvoice = new PLInvoice();
                    objInvoice.TrnInvoiceID = TrynParse.parseInt(ClientRequest["TrnIvoiceID"]);
                    objInvoice.TrnContractID = TrynParse.parseInt(ClientRequest[cboAddTrnContract.ID]);
                    objInvoice.MstCompanyID = TrynParse.parseInt(ClientRequest[cboAddCompany.ID]);
                    objInvoice.InvoiceDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtAddInvoiceDate.ID]).GetValueOrDefault();
                    objInvoice.MstPaymentLevelID = TrynParse.parseInt(ClientRequest[hdnPaymentLevelID.ID]);
                    objInvoice.PaymentLevelPer = TrynParse.parseDecimal(ClientRequest[txtAddContractPer.ID]);
                    objInvoice.GrossInvoiceAmount = TrynParse.parseDecimal(ClientRequest[txtGrossInvoiceAmt.ID]);
                    objInvoice.ServiceTaxPer = TrynParse.parseDecimal(ClientRequest[txtAddServiceTaxPer.ID]);
                    objInvoice.ServiceTaxAmount = TrynParse.parseDecimal(ClientRequest[txtServiceTaxAmt.ID]);
                    objInvoice.FinalInvoiceAmount = TrynParse.parseDecimal(ClientRequest[txtFinalInvoiceAmt.ID]);
                    objInvoice.IsActive = true;

                    try
                    {
                        int Result = new BL_Invoice().BL_InsertUpdateInvoiceTransactions(objInvoice);
                        if (Result > 0)
                        {
                            ClientResponse["strSaveMessage"] = GlobalDefaultValues.SaveMessage.Replace("XXX", "Invoice");
                            ClientResponse["strUpdateMessage"] = GlobalDefaultValues.UpdateMessage.Replace("XXX", "Invoice");
                            ClientResponse["IsSuccess"] = "1";
                            UI_SearchResult();
                        }
                        else
                        {
                            ClientResponse["strMessage"] = GlobalDefaultValues.SaveErrorMessage.Replace("XXX", "Invoice");
                            ClientResponse["IsSuccess"] = "0";
                        }
                    }
                    catch (Exception ex)
                    {
                        ClientResponse["strMessage"] = ex.Message;
                        CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent(), Track-InsertEditDetails");
                        ClientResponse["IsSuccess"] = "0";
                    }
                }
                else if (Track.Equals("AddRecord"))
                {
                    try
                    {
                        UI_AddRecord();
                    }
                    catch (Exception ex)
                    {
                        ClientResponse["strMessage"] = ex.Message;
                        CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent(), Track-AddRecord");
                        ClientResponse["IsSuccess"] = "0";
                    }
                }
                else if (Track.Equals("GetServiceTaxPer"))
                {
                    try
                    {
                        UI_GetServiceTaxPer();
                    }
                    catch (Exception ex)
                    {
                        ClientResponse["strMessage"] = ex.Message;
                        CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent(), Track-UI_GetServiceTaxPer");
                        ClientResponse["IsSuccess"] = "0";
                    }
                }
                else if (Track.Equals("DownloadInvoice"))
                {
                    try
                    {
                        UI_DownloadInvoice();
                    }
                    catch (Exception ex)
                    {
                        ClientResponse["strMessage"] = ex.Message;
                        CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent(), Track-DownloadInvoice");
                        ClientResponse["IsSuccess"] = "0";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent()");
        }
    }

    private void UI_GetServiceTaxPer()
    {
        PLInvoice objInvoice = new PLInvoice();
        objInvoice.InvoiceDate = TrynParse.parseDatetime(ClientRequest[txtAddInvoiceDate.ID]);
        MstServiceTax objServ = new BL_Invoice().BL_GetServiceTaxPer(objInvoice);
        decimal decServiceTaxPer = (objServ == null ? 0 : objServ.ServiceTaxPercentage.GetValueOrDefault());
        ClientResponse[hdnServiceTaxPer.ID] = decServiceTaxPer.ToString();
    }

    private void UI_SearchResult()
    {
        PLInvoice objInvoice = new PLInvoice();
        objInvoice.SearchCompanyIDs = ClientRequest[cboCompany.ID];
        objInvoice.SeachClientIDs = ClientRequest[cboClient.ID];
        objInvoice.SearchContractIDs = ClientRequest[cboContract.ID];
        objInvoice.SearchPaymentModeIDs = ClientRequest[cboPaymentMode.ID];
        objInvoice.SearchInvoiceNo = ClientRequest[txtInvoiceNo.ID];
        objInvoice.SeachContractNo = ClientRequest[txtContractNo.ID];

        objInvoice.SearchIsActive = true;//It will always load active invoices
        if (ClientRequest[cboCompletedStatus.ID] != "2")
            objInvoice.IsCompleted = (ClientRequest[cboCompletedStatus.ID] == "1") ? false : true;
        if (ClientRequest[txtInvoiceStartDate.ID] != "")
            objInvoice.SearchInvoiceStartDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceStartDate.ID]);
        if (ClientRequest[txtInvoiceEndDate.ID] != "")
            objInvoice.SearchInvoiceEndDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceEndDate.ID]);

        SessionInfo.prop_getObj.InvoiceEntrySearchCriteria = objInvoice;
        grdResult.DataSource = new BL_Invoice().BL_fnGetInvoiceTransactions(objInvoice);
        grdResult.DataBind();
        ClientResponse["grdResult"] = CommonUtil.GetRenderControl(grdResult);
    }

    private void UI_EditRecord()
    {
        int intInvoiceID = TrynParse.parseInt(ClientRequest[hdnInvoiceID.ID]);
        PLInvoice objInvoice = new BL_Invoice().BL_fnGetSingleInvoiceTransactions(new PLInvoice() { TrnInvoiceID = intInvoiceID });
        List<PLClient> objClients = new BL_Client().BL_fnGetClientNameList(new PLClient() { SearchIsActive = true, AddClientID = objInvoice.ClientID });
        CommonUtil.LoadDropdown(cboAddClient, objClients, "ClientID", "ClientName", "[Select Client]");

        List<PLContract> objContracts = new BL_Contract().BL_fnGetContractNameList(new PLContract() { SearchIsActive = true, AddContractID = objInvoice.ContractID });
        CommonUtil.LoadDropdown(cboAddContract, objContracts, "ContractID", "ContractName", "[Select Contract]");

        List<PLContract> objTrnContract = new BL_Invoice().BL_GetTrnContract(new PLContract() { SearchIsActive = true, ClientID = objInvoice.ClientID, CompanyID = objInvoice.CompanyID, ContractID = objInvoice.ContractID, PaymentModeID = objInvoice.PaymentModeID });
        CommonUtil.LoadDropdown(cboAddTrnContract, objTrnContract, "TrnContractID", "ContractNo", "[Select Contract No]");


        PLContract objContractList = new BL_Invoice().BL_GetTrnContractsDetails_Editing(new PLContract() { TrnContractID = objInvoice.TrnContractID, InvoiceID = objInvoice.TrnInvoiceID });
        ClientResponse[txtAddContractPer.ID] = objContractList.PaymentLevelPer.Value.ToString();
        ClientResponse[hdnCompletedContractPer.ID] = objContractList.CompletedContractPer.Value.ToString();
        ClientResponse[lblContractAmount.ID] = objContractList.ContractAmount.Value.ToString();
        ClientResponse[hdnCompletedInvAmount.ID] = objContractList.CompletedInvoiceAmount.Value.ToString();
        ClientResponse[hdnMaxContractInvoice.ID] = (objContractList.LastInvoiceDate == null ? "" : objContractList.LastInvoiceDate.Value.ToString("dd/mm/yyyy"));
        ClientResponse["IsLastPaymentMode"] = objContractList.IsLastPaymentMode.GetValueOrDefault().ToString();

        ClientResponse["cboAddClient"] = CommonUtil.GetRenderControl(cboAddClient);
        ClientResponse["cboAddContract"] = CommonUtil.GetRenderControl(cboAddContract);
        ClientResponse["cboAddTrnContract"] = CommonUtil.GetRenderControl(cboAddTrnContract);
        ClientResponse["RowID"] = ClientRequest["RowID"];

    }

    private void UI_AddRecord()
    {

    }

    private void UI_DownloadInvoice()
    {
        int intInvoiceID = TrynParse.parseInt(ClientRequest["InvoiceID"]);
        PLInvoice InvDet = new BL_Invoice().BL_ContractFilePath(new PLInvoice() { TrnInvoiceID = intInvoiceID });
        ClientResponse["InvoiceID"] = InvDet.TrnInvoiceID.ToString();
        ClientResponse["InvoiceNo"] = InvDet.InvoiceNo;
        ClientResponse["ClientName"] = InvDet.ClientName;
        ClientResponse["ContractPath"] = (InvDet.ContractFilePath ?? "");

    }

    private void UI_FillTrnContractsDetails()
    {
        PLContract objContract = new PLContract();
        objContract.TrnContractID = TrynParse.parseInt(ClientRequest[cboAddTrnContract.ID]);
        PLContract objContractList = new BL_Invoice().BL_GetPendingTrnContractsDetails(objContract);
        ClientResponse[lblPaymentMode.ID] = objContractList.PaymentModeName;
        ClientResponse[lblPaymentLevel.ID] = objContractList.PaymentLevelName;
        ClientResponse[hdnPaymentLevelID.ID] = objContractList.PaymentLevelID.Value.ToString();
        ClientResponse[txtAddContractPer.ID] = objContractList.PaymentLevelPer.Value.ToString();
        ClientResponse[hdnCompletedContractPer.ID] = objContractList.CompletedContractPer.Value.ToString();
        ClientResponse[lblContractAmount.ID] = objContractList.ContractAmount.Value.ToString();
        //ClientResponse[txtAddServiceTaxPer.ID] = objContractList.ServiceTax.Value.ToString();
        ClientResponse[hdnCompletedInvAmount.ID] = objContractList.CompletedInvoiceAmount.Value.ToString();
        ClientResponse[hdnMaxContractInvoice.ID] = (objContractList.LastInvoiceDate == null ? "" : objContractList.LastInvoiceDate.Value.ToString("dd/mm/yyyy"));
        ClientResponse["IsLastPaymentMode"] = objContractList.IsLastPaymentMode.GetValueOrDefault().ToString();
    }

    private void UI_FillClients(PLContract pObjContract)
    {
        List<PLClient> objClients = new BL_Invoice().BL_GetPendingClients(pObjContract);
        ClientResponse[cboAddClient.ID] = CommonUtil.LoadDropdownOptions(cboAddClient, objClients, "ClientID", "ClientName", "[Select Client]");
    }

    private void UI_FillContracts(PLContract pObjContract)
    {
        List<PLContract> objContractList = new BL_Invoice().BL_GetPendingContracts(pObjContract);
        ClientResponse[cboAddContract.ID] = CommonUtil.LoadDropdownOptions(cboAddContract, objContractList, "ContractID", "ContractName", "[Select Contract]");
    }

    private void UI_FillTrnContracts(PLContract pObjContract)
    {
        List<PLContract> objContractList = new BL_Invoice().BL_GetPendingTrnContracts(pObjContract);
        ClientResponse[cboAddTrnContract.ID] = CommonUtil.LoadDropdownOptions(cboAddTrnContract, objContractList, "TrnContractID", "ContractName", "[Select Contract]");
    }

    private void UI_DeleteRecord()
    {
        int intInvoiceID = TrynParse.parseInt(ClientRequest["InvoiceID"]);
        try
        {
            new BL_Invoice().BL_DeleteInvoice(new PLInvoice() { TrnInvoiceID = intInvoiceID });

            ClientResponse["strMessage"] = GlobalDefaultValues.DeleteMessage.Replace("XXX", "Invoice");
            ClientResponse["IsSuccess"] = "1";
            UI_SearchResult();
        }
        catch (Exception ex)
        {
            ClientResponse["strMessage"] = ex.Message;
            CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice Delete - Method: RaiseCallbackEvent(), Track-DeleteRecord");
            ClientResponse["IsSuccess"] = "0";
        }
    }
    protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Style["display"] = "none";
            e.Row.Cells[1].Style["display"] = "none";
            e.Row.Cells[2].Style["display"] = "none";
            e.Row.Cells[3].Style["display"] = "none";
            e.Row.Cells[4].Style["display"] = "none";
            e.Row.Cells[5].Style["display"] = "none";
            e.Row.Cells[6].Style["display"] = "none";
            e.Row.Cells[7].Style["display"] = "none";
            e.Row.Cells[8].Text = (e.Row.RowIndex + 1).ToString();
        }
        else if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Style["display"] = "none";
            e.Row.Cells[1].Style["display"] = "none";
            e.Row.Cells[2].Style["display"] = "none";
            e.Row.Cells[3].Style["display"] = "none";
            e.Row.Cells[4].Style["display"] = "none";
            e.Row.Cells[5].Style["display"] = "none";
            e.Row.Cells[6].Style["display"] = "none";
            e.Row.Cells[7].Style["display"] = "none";

        }
    }
    #endregion

}